package com.tsingteng.cosfun.ui.message.chat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.DialogListener;
import com.tsingteng.cosfun.base.BasePresenterFragment;
import com.tsingteng.cosfun.bean.ChatBean;
import com.tsingteng.cosfun.bean.UploadReportBean;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.DialogUtil;
import com.tsingteng.cosfun.utils.KeyBoardUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.TimeUtils;
import com.tsingteng.cosfun.widget.MyRecycleView;
import com.tsingteng.cosfun.widget.TitleView;
import com.tsingteng.cosfun.widget.dialog.BottomListDialog;
import com.umeng.message.PushAgent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

/**
 * 私信页面
 * 常胜
 * 2018.8.16
 */
public class ChatFragment extends BasePresenterFragment<ChatPresenter, ChatContract.IChatView> implements ChatContract.IChatView, BottomListDialog.OnClickBottomListListener
                                                                                                          ,DialogListener{
    @BindView(R.id.tv_chat_title)
    TitleView tvChatTitle;
    @BindView(R.id.rv_chat_recy)
    RecyclerView rvChatRecy;
    @BindView(R.id.et_chat_content)
    EditText etChatContent;
    @BindView(R.id.tv_send_message)
    TextView tvSendMessage;
    @BindView(R.id.rela_chat)
    RelativeLayout relaChat;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    private int page = 1;
    private String type = "MESSAGE";
    private List<String> reportList = new ArrayList<>();
    private BottomListDialog dialog;
    private int user_id;
    private List<ChatBean.ListBean> mList = new ArrayList<>();
    private ChatManyAdapter recyAdapter;
    private int count = 0;
    private String  mContent;
    private String title;

    public static ChatFragment newInstance() {
        return new ChatFragment();
    }

    @Override
    protected void initData(View rootView) {
        KeyBoardUtils.searchPoint(etChatContent);
        PushAgent.getInstance(getContext()).onAppStart();
        if (null == getActivity()){
            return;
        }
        Intent intent = getActivity().getIntent();
        user_id = intent.getIntExtra("user_id", 0);
        title = intent.getStringExtra("title");
        mPresenter.loginChatData(type, page, user_id);

        recyAdapter = new ChatManyAdapter(getContext(), mList);
        rvChatRecy.setLayoutManager(new LinearLayoutManager(getContext()));
        rvChatRecy.setAdapter(recyAdapter);

        tvChatTitle.setIvLeft(R.drawable.back_big_icon);
        tvChatTitle.setIvRight(R.drawable.more_icon);
        reportList.add("举报");
        reportList.add("拉黑");
        dialog = new BottomListDialog(getContext());
        dialog.setList(reportList);
        dialog.setOnClickBottomListListener(this);
        tvChatTitle.setTitle(title);
        //让recyclerview总是显示最下面
        tvChatTitle.setOnTitleClickListener(new TitleView.OnTitleClickListener() {
            @Override
            public void onLeft() {
                getActivity().finish();
            }

            @Override
            public void onRight() {
                dialog.show();
            }

            @Override
            public void onRight2() {

            }
        });
        tvSendMessage.setOnClickListener(v -> {
            mContent = etChatContent.getText().toString();
            if (!TextUtils.isEmpty(etChatContent.getText().toString())) {
                mPresenter.getReadPullBlackState(user_id);
                etChatContent.setText("");
            }
        });
        //软键盘回车监听
        etChatContent.setOnEditorActionListener((v, actionId, event) -> {
            //当actionId == XX_SEND 或者 XX_DONE时都触发
            //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
            //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
            if (actionId == EditorInfo.IME_ACTION_SEND
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                //处理事件
                KeyBoardUtils.closeKeyboard(getContext(), etChatContent);
                mContent = etChatContent.getText().toString();
                if (!TextUtils.isEmpty(etChatContent.getText().toString())) {
                    mPresenter.getReadPullBlackState(user_id);
//                        mPresenter.loginSendMessage(mContent,user_id);
//                            mList.add(new ChatBean.ListBean(mContent, TimeUtils.getCurTimeLong(), 0, 0, "MESSAGE", new ChatBean.ListBean.SourceBean(LogonUtils.getProFildId(),
//                                    LogonUtils.getNickIcon(), LogonUtils.getNickName(), 0), 0, new ChatBean.ListBean.TargetBean(0), "", TimeUtils.getCurTimeLong()));
//                            rvChatRecy.scrollToPosition(mList.size() - 1);
                    etChatContent.setText("");
                }
            }
            return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
        });

        relaChat.setOnClickListener(view -> KeyBoardUtils.closeKeyboard(getContext(), etChatContent));
        mRefreshLayout.setOnRefreshListener(refreshlayout -> {
            page = 1;
            mList.clear();
            mPresenter.loginChatData(type, page, user_id);
            refreshlayout.finishRefresh();
        });
        //加载更多
        mRefreshLayout.setOnLoadMoreListener(RefreshLayout::finishLoadMore);

        KeyBoardUtils.observeSoftKeyboard(getActivity(), new KeyBoardUtils.OnSoftKeyboardChangeListener() {
            @Override
            public void onSoftKeyBoardChange(int softKeybardHeight, boolean visible) {
                if (visible && rvChatRecy !=null && mList !=null && mList.size()>0) {
                    rvChatRecy.scrollToPosition(mList.size()-1);
                }
            }
        });
    }



    @Override
    protected ChatPresenter createPresenter() {
        return new ChatPresenter();
    }

    @Override
    protected View initHeader() {
        return null;
    }

    @Override
    protected MyRecycleView createRecycleView() {
        return null;
    }

    @Override
    protected BaseQuickAdapter createAdapter() {
        return null;
    }

    @Override
    protected void refresh() {

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onLoadMoreRequested() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chat;
    }

    @Override
    public void showChatData(ChatBean chatBean) {
        if(chatBean.getList()==null)return;
        List<ChatBean.ListBean> chatList = chatBean.getList();
        Collections.reverse(chatList);
        mList.addAll(chatList);
        recyAdapter.notifyDataSetChanged();
        if (chatList.size()==0) return;
        mPresenter.loginChatRead("MESSAGE",chatList.get(chatList.size()-1).getId(),chatList.get(chatList.size()-1).getSource().getId());
        if(count == 0){
            rvChatRecy.scrollToPosition(mList.size()-1);
            count = 1;
        }
    }

    @Override
    public void showPullBlackResult(UploadReportBean uploadReportBean) {
        showToast(uploadReportBean.toString());
    }

    @Override
    public void showReadPullBlackStateResult(int data) {
          if (-1 == data){
              mPresenter.loginSendMessage(mContent,user_id);
          }else{
              @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
              String content=getResources().getString(R.string.comment_handle,title);
//              String message=String.format(content,title);
             DialogUtil.getContentCommentDialog(getActivity(),content,user_id,this);
          }
    }

    @Override
    public void sendMessageResult(Integer integer) {
        if(integer == 1){
//            showToast("消息发送成功！");
            //消息发送成功之后将纤细发送的时间给存起来  下次是否显示时间

            AppUtils.setChatTime();
            if (null !=mList && mList.size() != 0){
                mList.clear();
            }
            mPresenter.loginChatData(type, page, user_id);
            count=0;
        }
    }

    @Override
    public void showFailResult(int errorCode, String errorMsg) {
        if (50072 ==errorCode){
            confirmDialog();
        }
    }

    @Override
    public void showCancelPullBlack(int data) {
        if (1 == data) {
            showToast(getResources().getString(R.string.cancel_black_success));
        }
    }

    @Override
    public void showReadResult(Integer integer) {
        Log.e("isRead",integer+"");
    }

    @Override
    public void onClickItem(BaseQuickAdapter adapter, View view, int position, List<String> list) {
        if(mList.get(position)==null)return;
        ChatBean.ListBean listBean = (ChatBean.ListBean) mList.get(position);

        if(listBean != null){
            switch (list.get(position)) {
                case "举报":
                    Navigate.startReportList(getContext(), 4, user_id);
                    dialog.dissMiss();
                    break;
                case "拉黑":
                    mPresenter.loginPullBlack(user_id + "");
                    dialog.dissMiss();
                    break;
            }
        }
    }

    @Override
    public void onClickBottom() {
        if (dialog != null) {
            dialog.dissMiss();
        }
    }
    /**
     * 确认弹窗
     */
    private void confirmDialog() {
        @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
        String content = getResources().getString(R.string.comment_private,title);
        DialogUtil.getContentDialog(getActivity(),content);
    }

    @Override
    public void clickDialog(long workId) {
        mPresenter.getCancelPullBlack(workId);
    }
}
